import { Form } from 'ant-design-vue'
import { type Ref, onMounted, ref } from 'vue'

import { materialApi } from '@/apis'
import { GetVideoLimitRes } from '@/apis/materialTypes'

import type { SearchParams, VideoForm } from '../types'

const { useForm } = Form

type Params = {
  searchParams: Ref<SearchParams>
  handleGetVideoList: PromiseFunc
  handleGetVideoLimit: PromiseFunc
  handleGetGroupList: PromiseFunc
}

export function useToolbar({
  searchParams,
  handleGetVideoList,
  handleGetVideoLimit,
  handleGetGroupList
}: Params) {
  const showAddVideo = ref(false)
  const addVideoLoading = ref(false)
  const addVideoFormModel = ref({
    name: '',
    channel: undefined,
    cover: '',
    description: '',
    groupId: 2,
    size: undefined,
    suffix: '',
    videoUrl: ''
  } as Partial<VideoForm>)
  const addVideoFormRules = ref({
    name: [{ required: true, message: '请输入' }],
    channel: [{ required: true, message: '请选择' }],
    videoUrl: [{ required: true, message: '请上传' }],
    cover: [{ required: true, message: '请上传' }]
  } as FormRules)
  const typeOptions = ref([
    { label: '不限', value: '' },
    { label: 'MP4', value: 'MP4' },
    { label: 'FLV', value: 'FLV' }
  ] as OptionItem[])
  const videoLimit = ref({
    limit: 0,
    num: 0
  } as GetVideoLimitRes)

  const addVideoFormRef = useForm(addVideoFormModel, addVideoFormRules)

  /** 显示新建弹窗 */
  function handleShowAddVideo() {
    showAddVideo.value = true
  }

  /** 关闭新建弹窗 */
  function handleCloseAddVideo() {
    addVideoFormRef.resetFields()
    showAddVideo.value = false
    addVideoLoading.value = false
  }

  /** 新建视频 */
  function addVideo() {
    addVideoFormRef
      .validate()
      .then(async () => {
        try {
          addVideoLoading.value = true

          await materialApi.createVideo(addVideoFormModel.value)
          handleCloseAddVideo()
          handleGetVideoList()
          handleGetVideoLimit()
          handleGetGroupList()
        } finally {
          addVideoLoading.value = false
        }
      })
      .catch(() => {})
  }

  /** 格式搜索 */
  function handleFormatSearch() {
    handleGetVideoList()
  }

  /** 输入框搜索 */
  function handleInputSearch(value: string) {
    searchParams.value.name = value
    handleGetVideoList()
  }

  /** 获取限制百分比 */
  function getLimitPercent() {
    return videoLimit.value.limit
      ? (videoLimit.value.num / videoLimit.value.limit) * 100
      : 0
  }

  return {
    showAddVideo,
    addVideoLoading,
    addVideoFormRef,
    addVideoFormModel,
    typeOptions,
    videoLimit,
    handleShowAddVideo,
    handleCloseAddVideo,
    addVideo,
    handleFormatSearch,
    handleInputSearch,
    getLimitPercent
  }
}
